package com.xwt.pdfutils;

import com.itextpdf.text.pdf.PdfReader;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;
import com.xwt.executor.Stc;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class PdfUtil {

    /***
     * PDF文件转PNG图片，全部页数
     *
     * @param PdfFilePath pdf完整路径
     * @param dstImgFolder 图片存放的文件夹
     * @param dpi dpi越大转换后越清晰，相对转换速度越慢
     * @return
     */
    public void pdf2Image(String PdfFilePath, String dstImgFolder, Integer dpi, Integer th) throws InterruptedException {
        if (th == null) {
            th = 5;
        }
        ExecutorService executorService =
                new ThreadPoolExecutor(th, th, 60L, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(50));
        long l = System.currentTimeMillis();
        File file = new File(PdfFilePath);
        PDDocument pdDocument;
        try {
            String imgPDFPath = file.getParent();
            int dot = file.getName().lastIndexOf('.');
            String imagePDFName = file.getName().substring(0, dot); // 获取图片文件名
            String imgFolderPath = null;
            if (dstImgFolder.equals("")) {
                imgFolderPath = imgPDFPath + File.separator + imagePDFName;// 获取图片存放的文件夹路径
            } else {
                imgFolderPath = dstImgFolder + File.separator + imagePDFName;
            }

            if (createDirectory(imgFolderPath)) {

                pdDocument = PDDocument.load(file);
                PDFRenderer renderer = new PDFRenderer(pdDocument);
                /* dpi越大转换后越清晰，相对转换速度越慢 */
                PdfReader reader = new PdfReader(PdfFilePath);
                int pages = reader.getNumberOfPages();
                // 进行page页码数计算
                List<Integer> page = doCommont(pages);
                for (int i = 0; i < page.size(); i++) {
                    if (i == page.size() - 1) {
                        executorService.execute(new Stc(dpi, imagePDFName, imgFolderPath, renderer, page.get(i) * 30, pages));
                    } else {
                        executorService.execute(new Stc(dpi, imagePDFName, imgFolderPath, renderer, page.get(i) * 30, page.get(i + 1) * 30));
                    }
//					doImage(dpi, imagePDFName, imgFolderPath, renderer, page.get(i),pages);
                }
                StringBuffer imgFilePath = null;
            } else {
                System.out.println("PDF文档转PNG图片失败：" + "创建" + imgFolderPath + "失败");
                System.exit(0);
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            System.out.println("程序执行中......");
            executorService.shutdown();
            while (true) {
                //等待线程池所有的任务执行完
                if (executorService.isTerminated()) {
                    break;
                }
            }
            long l1 = System.currentTimeMillis();
            l = l1 - l;
            System.out.println("PDF文档转PNG图片成功！共耗时"+ l / 1000 / 60+"分钟");
        }
    }

    private void doImage(int dpi, String imagePDFName, String imgFolderPath, PDFRenderer renderer, int startPages, int endPages) throws IOException {
        StringBuffer imgFilePath;
        for (int i = startPages; i < endPages; i++) {
            String imgFilePathPrefix = imgFolderPath + File.separator + imagePDFName;
            imgFilePath = new StringBuffer();
            imgFilePath.append(imgFilePathPrefix);
            imgFilePath.append("_");
            imgFilePath.append(String.valueOf(i + 1));
            imgFilePath.append(".png");
            File dstFile = new File(imgFilePath.toString());
            BufferedImage image = renderer.renderImageWithDPI(i, dpi);
            ImageIO.write(image, "png", dstFile);
        }
    }

    private List<Integer> doCommont(int pages) {

        // 做数据处理
        ArrayList integers = new ArrayList<Integer>();
        int i = pages / 30;
        for (int j = 0; j <= i; j++) {
            integers.add(j);
        }
        return integers;
    }

    private boolean createDirectory(String folder) {
        File dir = new File(folder);
        if (dir.exists()) {
            return true;
        } else {
            return dir.mkdirs();
        }
    }
}
